package com.domor.service.project;

import com.domor.dao.project.CustomerDao;
import com.domor.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class CustomerService {

    @Autowired
    private CustomerDao dao;

    public Map<String,Object> getById(int id) {
        return dao.getById(id);
    }

    public List<Map<String, Object>> query(Map<String, Object> params) {
        return dao.query(params);
    }

    public List<Map<String, Object>> getContacts(int id){
        return dao.getContacts(id);
    }

    @Transactional
    public void insert(Map<String, Object> customer, String username) {
        customer.put("loginUser", username);
        dao.insert(customer);

        int customerId = MapUtils.getIntValue(customer, "id");
        List<Map> contacts = (List<Map>) customer.get("contacts");
        for (Map contact : contacts) {
            contact.put("customerId", customerId);
            contact.put("loginUser", username);
            dao.insertContact(contact);
        }
    }

    @Transactional
    public void update(Map<String, Object> customer, String username){
        customer.put("loginUser", username);
        dao.update(customer);

        dao.deleteContact(customer);

        int customerId = MapUtils.getIntValue(customer, "id");
        List<Map> contacts = (List<Map>)customer.get("contacts");
        for (Map contact : contacts) {
            contact.put("customerId", customerId);
            contact.put("loginUser", username);
            dao.insertContact(contact);
        }
    }

    @Transactional
    public void delete(Map<String, Object> params){
        dao.delete(params);
        dao.deleteContact(params);
    }

}
